package dev.yorkecao.demo.mybatis.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.ds1")
    public DataSource getDs1DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.ds2")
    public DataSource getDs2DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public MultipleDataSource getMultipleDataSource() {
        Map<Object, Object> dataSources = new HashMap<>();
        dataSources.put("ds1", getDs1DataSource());
        dataSources.put("ds2", getDs2DataSource());

        return new MultipleDataSource(getDs1DataSource(), dataSources);
    }
}
